﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Profiling;

namespace SoarD.Pandora.Console
{
    public partial class PdrConsoleWindow
    {
        private sealed class RunTimeMemoryWindow<T> : ScrollWindowBase where T : UnityEngine.Object
        {
            private const int ShowSampleCount = 300;

            private DateTime m_SampleTime = DateTime.MinValue;
            private long m_SampleSize;
            private long m_DuplicateSampleSize;
            private int m_DuplicateSimpleCount;
            private List<Sample> m_Samples = new List<Sample>();

            protected override void OnDrawScrollableWindow()
            {
                string typeName = typeof(T).Name;
                GUILayout.Label(string.Format("<b>{0}内存详情:</b>", typeName));
                GUILayout.BeginVertical("box");
                {
                    if (GUILayout.Button(string.Format("获取{0}当前详情", typeName)))
                    {
                        TakeSample();
                    }
                    GUILayout.Space(spaceHeight);
                    if (m_SampleTime <= DateTime.MinValue)
                    {
                        GUILayout.Label(string.Format("<b>点击按钮获取当前{0}详情</b>", typeName));
                        GUILayout.Space(spaceHeight);
                    }
                    else
                    {
                        if (m_DuplicateSimpleCount > 0)
                        {
                            GUILayout.Label(string.Format("<b>{1} {2}s ({3}), 可能重复:{4} {2}s ({5})</b>",
                                m_SampleTime.ToString("yyyy-MM-dd HH:mm:ss"), m_Samples.Count, typeName,
                                GetSizeString(m_SampleSize), m_DuplicateSimpleCount,
                                GetSizeString(m_DuplicateSampleSize)));
                        }
                        else
                        {
                            GUILayout.Label(string.Format("<b>[{0}]: {1} {2}s ({3})</b>",
                                m_SampleTime.ToString("yyyy-MM-dd HH:mm:ss"), m_Samples.Count, typeName,
                                GetSizeString(m_SampleSize)));
                        }

                        if (m_Samples.Count > 0)
                        {
                            GUILayout.BeginHorizontal();
                            {
                                GUILayout.Label(string.Format("<b>{0} 名字</b>", typeName));
                                GUILayout.Label("<b>类型</b>", GUILayout.Width(240f));
                                GUILayout.Label("<b>大小</b>", GUILayout.Width(120));
                            }
                            GUILayout.EndHorizontal();
                        }

                        int count = 0;
                        for (int i = 0; i < m_Samples.Count; i++)
                        {
                            GUILayout.BeginHorizontal();
                            {
                                GUILayout.Label(m_Samples[i].Highlight
                                    ? string.Format("<color=yellow>{0}</color>", m_Samples[i].Name)
                                    : m_Samples[i].Name);
                                GUILayout.Label(
                                    m_Samples[i].Highlight
                                        ? string.Format("<color=yellow>{0}</color>", m_Samples[i].Type)
                                        : m_Samples[i].Type, GUILayout.Width(240));
                                GUILayout.Label(
                                    m_Samples[i].Highlight
                                        ? string.Format("<color=yellow>{0}</color>", GetSizeString(m_Samples[i].Size))
                                        : GetSizeString(m_Samples[i].Size), GUILayout.Width(150));
                            }
                            GUILayout.EndHorizontal();

                            count++;
                            if (count >= ShowSampleCount)
                            {
                                break;
                            }
                        }
                    }
                }
                GUILayout.EndVertical();
            }

            private void TakeSample()
            {
                m_SampleTime = DateTime.Now;
                m_SampleSize = 0L;
                m_DuplicateSampleSize = 0L;
                m_DuplicateSimpleCount = 0;
                m_Samples.Clear();

                T[] samples = Resources.FindObjectsOfTypeAll<T>();
                for (int i = 0; i < samples.Length; i++)
                {
                    long sampleSize = Profiler.GetRuntimeMemorySize(samples[i]);
                    m_SampleSize += sampleSize;
                    m_Samples.Add(new Sample(samples[i].name, samples[i].GetType().Name, sampleSize));
                }

                m_Samples.Sort(SampleComparer);

                for (int i = 1; i < m_Samples.Count; i++)
                {
                    if (m_Samples[i].Name == m_Samples[i - 1].Name && m_Samples[i].Type == m_Samples[i - 1].Type &&
                        m_Samples[i].Size == m_Samples[i - 1].Size)
                    {
                        m_Samples[i].Highlight = true;
                        m_DuplicateSampleSize += m_Samples[i].Size;
                        m_DuplicateSimpleCount++;
                    }
                }
            }

            private string GetSizeString(long size)
            {
                if (size < 1024L)
                {
                    return string.Format("{0} Bytes", size.ToString());
                }

                if (size < 1024L * 1024L)
                {
                    return string.Format("{0} KB", (size / 1024f).ToString("F2"));
                }

                if (size < 1024L * 1024L * 1024L)
                {
                    return string.Format("{0} MB", (size / 1024f / 1024f).ToString("F2"));
                }

                if (size < 1024L * 1024L * 1024L * 1024L)
                {
                    return string.Format("{0} GB", (size / 1024f / 1024f / 1024f).ToString("F2"));
                }

                return string.Format("{0} TB", (size / 1024f / 1024f / 1024f / 1024f).ToString("F2"));
            }

            private int SampleComparer(Sample a, Sample b)
            {
                int result = b.Size.CompareTo(a.Size);
                if (result != 0)
                {
                    return result;
                }

                result = string.Compare(a.Type, b.Type, StringComparison.Ordinal);
                if (result != 0)
                {
                    return result;
                }

                return string.Compare(a.Name, b.Name, StringComparison.Ordinal);
            }

            private sealed class Sample
            {
                private readonly string m_Name;
                private readonly string m_Type;
                private readonly long m_Size;

                public Sample(string name, string type, long size)
                {
                    m_Name = name;
                    m_Type = type;
                    m_Size = size;
                    Highlight = false;
                }

                public string Name
                {
                    get { return m_Name; }
                }

                public string Type
                {
                    get { return m_Type; }
                }

                public long Size
                {
                    get { return m_Size; }
                }

                public bool Highlight { get; set; }
            }
        }
    }
}